package com.astoolkit.workflow.task.io
{
	import com.astoolkit.workflow.BaseTask;
	
	import flash.filesystem.File;
	import flash.net.FileFilter;
	
	import mx.collections.ArrayCollection;
	
	[SyncTask]
	public class GetFilesList extends BaseTask
	{
		public var location : String;
		public var fileFilter : Array;
		public var simpleArrayOutput : Boolean;
		public var recursive : Boolean;
		
		override public function begin():void
		{
			super.begin();
			var aLocation : String = location;
			if( !aLocation )
			{
				aLocation = filteredPipelineData as String;
				if( !aLocation )
				{
					fail( "No location provided either explicitly or via the pipeline" );
					return;
				}
			}
			var files : Array;
			try
			{
				var file : File = new File( location );
				if( file.isDirectory )
				{
					files = listDirectory( file, recursive ); 
					if( simpleArrayOutput )
						_pipelineData = files;
					else
						_pipelineData = new ArrayCollection( files );
				}
				complete();
			}
			catch( e : Error ) 
			{
				fail( "Error reading files from location '" + aLocation + " \n\n" + e.getStackTrace() );
			}
		}
		
		private function listDirectory( inDir : File, inRecursive : Boolean = false ) : Array 
		{
			var out : Array;
			if( fileFilter )
			{
				out = inDir.getDirectoryListing().filter( 
					function callback( inFile : File, inIndex : int, inArray : Array ) : Boolean
					{
						for each( var f : Object in fileFilter )
						{
							var re : RegExp = f is RegExp ? f : new RegExp( f );
							if( inFile.name.match( re ) )
								return true;
						}
						return false;
					} );
			}
			
			if( recursive )
			{
				for each( var file : File in inDir.getDirectoryListing() )
				{
					if( file.isDirectory )
						out = out.concat( listDirectory( file, true ) );
				}
			}
			return out;
		}
	}
}